package com.zhsj.OkeHomeConsumption.ui.fragment.integral.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.base.BaseDialog;
import com.huantansheng.easyphotos.EasyPhotos;
import com.orhanobut.hawk.Hawk;
import com.tencent.bugly.crashreport.biz.UserInfoBean;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.empty.IntegralBean;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.QRCodeUtil;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.TimeOutHandler;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.ui.activity.WebActivity;
import com.zhsj.OkeHomeConsumption.ui.fragment.integral.adapter.IntegralAdapter;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 赚积分
 */
public class IntegralActivity extends MyActivity {
    @BindView(R.id.recycle)
    RecyclerView recycle;
    @BindView(R.id.rules_image)
    ImageView rulesImage;
    @BindView(R.id.invite_image)
    ImageView inviteImage;
    @BindView(R.id.integral_text)
    TextView integralText;
    @BindView(R.id.integral_person_text)
    TextView integralPersonText;
    @BindView(R.id.icon_jiantou)
    ImageView iconJiantou;

    private BaseDialog pDialogUtils;
    public TimeChecker timeChecker;
    private List<IntegralBean> mIntegrallist;
    private ArrayList<IntegralBean> mServiceIntegrallist;
    private IntegralAdapter integralAdapter;

    //多过五条是否是展开状态
    private boolean isAll = false;
    //用户信息
    private FormalUserInfo formalUserInfo;
    //用户id
    private String userId;
    private Bitmap bmp = null;
    Bitmap qrImage = null;
    //分享链接
    private String shareUrl;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_integral;
    }

    @Override
    protected int getTitleId() {
        return R.id.title_back;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        formalUserInfo = Hawk.get(Constants.SHARED_PERFERENCE_USERINFO);
        userId = String.valueOf(formalUserInfo.getId());
        shareUrl = OkeHomeConsumptionApi.ELVDOU_BASEURL_H5 + "app/h5/platform/12.html?userid=" + userId +"&invite=" + userId +"&type=1&rtype=1";
        initRecycle();
        getIntegralMessage();
        getIntegralsList();
    }

    @OnClick({R.id.rules_image, R.id.invite_image, R.id.integral_strategy_image, R.id.invite_face_image, R.id.icon_jiantou})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rules_image:
                //活动规则
                Intent intent = new Intent(getActivity(), WebActivity.class).putExtra("url",OkeHomeConsumptionApi.ELVDOU_BASEURL_H5 + "app/h5/platform/32.html");
                startActivity(intent);
                break;
            case R.id.invite_image:
                //立即邀请
                shareApp("疯了，通过聚联惠的合作商家消费，竟然可以全额返还",
                        "85%以上的家庭，尽管精打细算，节衣缩食，却仍然捉襟见肘。其根本原因，是因为绝大部分的家庭，除了固定的工资，再没有其他的经济来源。那么，有没有可能让您化出去的钱，又能全额的回到您的钱包呢？",
                        shareUrl);
                break;
            case R.id.integral_strategy_image:
                //赚积分攻略
                Intent intent2 = new Intent(getActivity(), WebActivity.class).putExtra("url",OkeHomeConsumptionApi.ELVDOU_BASEURL_H5 + "app/h5/platform/31.html");
                startActivity(intent2);
                break;
            case R.id.invite_face_image:
                //面对面邀请
                Intent intent1 = new Intent(this, InviteFaceActivity.class);
                startActivity(intent1);
                break;
            case R.id.icon_jiantou:
                //箭头
                mIntegrallist.clear();
                if (isAll){
                    isAll = false;
                    getFiveList();
                    iconJiantou.setImageResource(R.mipmap.icon_jiantou_down);
                }else {
                    isAll = true;
                    mIntegrallist.addAll(mServiceIntegrallist);
                    iconJiantou.setImageResource(R.mipmap.icon_jiantou_up);
                }
                integralAdapter.setNewData(mIntegrallist);
                break;
        }
    }

    /**
     * 获取前五条数据
     */
    private void getFiveList(){
        for (int i = 0; i < 5; i ++){
            mIntegrallist.add(mServiceIntegrallist.get(i));
        }
    }

    /**
     * 分享
     *
     * @param title
     * @param content
     * @param url
     */
    private void shareApp(String title, String content, final String url) {
        final UMWeb web = new UMWeb(url);
        web.setTitle(title);//标题
        web.setDescription(content);//描述
        web.setThumb(new UMImage(getActivity(), R.mipmap.androidicon1));
        new ShareAction(getActivity())
                .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                .addButton("复制链接", "copy", "umeng_copy", "umeng_copy")
                .addButton("二维码", "code", "umeng_code", "umeng_code")
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        if (share_media == null) {
                            if (snsPlatform.mKeyword.equals("copy")) {
                                //复制链接
                                copyText(getApplicationContext(), url);
                                toast("复制成功");
                            } else if (snsPlatform.mKeyword.equals("code")) {
                                //二维码
                                bmp = BitmapFactory.decodeResource(getResources(), R.drawable.qrcode_julianhui).copy(Bitmap.Config.RGB_565, true);
                                qrImage = QRCodeUtil.createQRImage(shareUrl);
                                EasyPhotos.addWatermark(qrImage, bmp, 1800, 250, 250, true);
                                final UMImage image = new UMImage(getActivity(), bmp);//bitmap文件
                                new ShareAction(getActivity()).setPlatform(0 == 0 ? SHARE_MEDIA.WEIXIN : SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                                        .withMedia(image)
                                        .share();
                            }
                        } else {
                            new ShareAction(getActivity()).setPlatform(share_media).setCallback(umShareListener)
                                    .withMedia(web)
                                    .share();
                        }
                    }
                }).open();
    }

    public static void copyText(Context context, CharSequence textCopy) {
        if (Build.VERSION.SDK_INT > 11) {
            ClipboardManager c = (ClipboardManager) context
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            c.setText(textCopy);

        } else {
            android.text.ClipboardManager c = (android.text.ClipboardManager) context
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            c.setText(textCopy);
        }

    }

    /**
     * @Fields umShareListener : TODO 监听分享后的状态
     */
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            toast("分享活动成功啦");

        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {

            toast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {

            toast("分享取消了");
        }
    };

    private void getIntegralMessage() {
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);

        paramMaps.put("optType", String.valueOf(2));
        mLogOnHashMap.put("optType", String.valueOf(2));

        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.get(OkeHomeConsumptionApi.ELVDOU_INTEGRAL_MESSAGE, paramMaps, new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                super.onSuccess(statusCode, content);
                LogUtils.e("获取积分信息", content);
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        JSONObject jsonobj = jsonOBJ.optJSONObject("data");
                        integralText.setText(jsonobj.optString("integral"));
                        integralPersonText.setText(jsonobj.optString("inviteUsers"));
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        // token过期
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    }
                } catch (JSONException ex) {
                    Log.e("Integrals", "积分列表");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                super.onFailure(e);
            }
        });
    }

    /**
     * 获取积分列表
     */
    private void getIntegralsList() {
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);
        //页码
        paramMaps.put("pageNum", String.valueOf(1));
        mLogOnHashMap.put("pageNum", String.valueOf(1));
        //每页数量
        paramMaps.put("pageSize", String.valueOf(20));
        mLogOnHashMap.put("pageSize", String.valueOf(20));

        paramMaps.put("optType", String.valueOf(2));
        mLogOnHashMap.put("optType", String.valueOf(2));

        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.get(OkeHomeConsumptionApi.ELVDOU_INTEGRALS, paramMaps, new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                super.onSuccess(statusCode, content);
                LogUtils.e("获取积分正", content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        JSONObject jsonobj = jsonOBJ.optJSONObject("data");
                        JSONArray arr = jsonobj.optJSONArray("jsonObj");
                        mServiceIntegrallist = new Gson().fromJson(arr.toString(), new
                                TypeToken<ArrayList<IntegralBean>>() {
                                }.getType());
                        if (mServiceIntegrallist.size() > 5) {
                            iconJiantou.setVisibility(View.VISIBLE);
                            getFiveList();
                        } else {
                            iconJiantou.setVisibility(View.GONE);
                            mIntegrallist.addAll(mServiceIntegrallist);
                        }
                        integralAdapter.setNewData(mIntegrallist);

                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        // token过期
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    }
                } catch (JSONException ex) {
                    Log.e("Integrals", "积分列表");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
            }
        });
    }


    /**
     * 初始化recycle
     */
    private void initRecycle() {
        pDialogUtils = new BaseDialog(this);
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        mServiceIntegrallist = new ArrayList<IntegralBean>();
        mIntegrallist = new ArrayList<IntegralBean>();

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        //解决嵌套卡顿情况
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        recycle.setHasFixedSize(true);
        recycle.setNestedScrollingEnabled(false);//禁止滑动
        //设置布局管理器
        recycle.setLayoutManager(layoutManager);

        integralAdapter = new IntegralAdapter(R.layout.item_integral);
        recycle.setAdapter(integralAdapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

}
